package util;

import org.joda.time.DateTime;
import org.opensaml.DefaultBootstrap;
import org.opensaml.saml2.core.Artifact;
import org.opensaml.saml2.core.ArtifactResolve;
import org.opensaml.saml2.core.Issuer;
import org.opensaml.saml2.core.impl.ArtifactResolveMarshaller;
import org.opensaml.xml.Configuration;
import org.opensaml.xml.XMLObjectBuilderFactory;
import org.opensaml.xml.util.XMLHelper;
import org.w3c.dom.Element;

public class SamlRequest {
	
	static{
		try{
			DefaultBootstrap.bootstrap() ;
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	
	public static void main(String[] args){
		try{
			System.out.println(SamlRequest.request("aaa", "code"));
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public static String request(String author, String code)throws Exception{
		XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();   
		ArtifactResolve artifactResolve = (ArtifactResolve)builderFactory.getBuilder(ArtifactResolve.DEFAULT_ELEMENT_NAME).buildObject(ArtifactResolve.DEFAULT_ELEMENT_NAME); 
		
		Issuer issuer = (Issuer)builderFactory.getBuilder(Issuer.DEFAULT_ELEMENT_NAME)
				.buildObject(Issuer.DEFAULT_ELEMENT_NAME); 
		issuer.setValue(author);
		artifactResolve.setIssuer(issuer); 
		artifactResolve.setIssueInstant(new DateTime());
		Artifact artifact = (Artifact)builderFactory.getBuilder(Artifact.DEFAULT_ELEMENT_NAME).buildObject(Artifact.DEFAULT_ELEMENT_NAME); 
		artifact.setArtifact(code);
		
		artifactResolve.setArtifact(artifact);
		
		ArtifactResolveMarshaller marshaller = new ArtifactResolveMarshaller();
		Element plaintextElement = marshaller.marshall(artifactResolve);
		String originalAssertionString = XMLHelper.nodeToString(plaintextElement);
		
		return originalAssertionString;
	}

}
